<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 发送日志
 * @param $url
 * @param $result_data
 * @param string $send_data
 * @param $filename
 * @return int
 */
function send_log($url,$result_data,$send_data='',$filename){
    $log = date('Y-m-d H:i:s') . "--------------------send--starts-------------------------\n";
    $log .= 'url-is--' . $url . "\n";
    $log .= 'session_id-is--' . session_id() . "\n";
    $log .= 'send-data-is--' . json_encode($send_data,JSON_UNESCAPED_UNICODE) . "\n";
    $log .= 'receive-data-is--' . $result_data . "\n";
    $path = \think\facade\App::getRootPath() . '/logs/' . $filename . '.log';
    file_put_contents($path,$log,FILE_APPEND);
    return 1;
}

/**
 * 接受日志
 * @param $data
 * @param $filename
 * @return int
 */
function accept_log($data,$filename){
    $request = Request::instance();
    $log = date('Y-m-d H:i:s') . "--------------------request-starts-----------------------\n";
    $log .= 'url-is--' . $request->url(true) . "\n";
    $log .= 'accept-data-is--' . json_encode($data,JSON_UNESCAPED_UNICODE) . "\n";
    $path = \think\facade\App::getRootPath() . '/logs/' . $filename . '.log';
    file_put_contents($path,$log,FILE_APPEND);
    return 1;
}

/**
 * 获取上传图片签名
 * @param string $method 请求类型 method
 * @param string $pathname 文件名称
 * @return string 签名字符串
 */
function get_authorization($method, $pathname){
    //获取个人 API 密钥 https://console.qcloud.com/capi
    $SecretId = 'AKIDSr5IKCwy770iEJnCxb4TgigXHUXQelAP';
    $SecretKey = 'CC2hARWP9hUFtSr693mJesulRwX4Tmz3';
    //整理参数
    $queryParams = array();
    $headers = array();
    $method = strtolower($method ? $method : 'get');
    $pathname = $pathname ? $pathname : '/';
    substr($pathname, 0, 1) != '/' && ($pathname = '/' . $pathname);
    // 工具方法
    function getObjectKeys($obj){
        $list = array_keys($obj);
        sort($list);
        return $list;
    }
    function obj2str($obj){
        $list = array();
        $keyList = getObjectKeys($obj);
        $len = count($keyList);
        for ($i = 0; $i < $len; $i++) {
            $key = $keyList[$i];
            $val = isset($obj[$key]) ? $obj[$key] : '';
            $key = strtolower($key);
            $list[] = rawurlencode($key) . '=' . rawurlencode($val);
        }
        return implode('&', $list);
    }
    //签名有效起止时间
    $now = time() - 1;
    $expired = $now + 600; //签名过期时刻，600 秒后
    //要用到的 Authorization 参数列表
    $qSignAlgorithm = 'sha1';
    $qAk = $SecretId;
    $qSignTime = $now . ';' . $expired;
    $qKeyTime = $now . ';' . $expired;
    $qHeaderList = strtolower(implode(';', getObjectKeys($headers)));
    $qUrlParamList = strtolower(implode(';', getObjectKeys($queryParams)));
    //签名算法说明文档：https://www.qcloud.com/document/product/436/7778
    //步骤一：计算 SignKey
    $signKey = hash_hmac("sha1", $qKeyTime, $SecretKey);
    //步骤二：构成 FormatString
    $formatString = implode("\n", array(strtolower($method), $pathname, obj2str($queryParams), obj2str($headers), ''));
    //步骤三：计算 StringToSign
    $stringToSign = implode("\n", array('sha1', $qSignTime, sha1($formatString), ''));
    //步骤四：计算 Signature
    $qSignature = hash_hmac('sha1', $stringToSign, $signKey);
    //步骤五：构造 Authorization
    $authorization = implode('&', array(
        'q-sign-algorithm=' . $qSignAlgorithm,
        'q-ak=' . $qAk,
        'q-sign-time=' . $qSignTime,
        'q-key-time=' . $qKeyTime,
        'q-header-list=' . $qHeaderList,
        'q-url-param-list=' . $qUrlParamList,
        'q-signature=' . $qSignature
    ));
    return $authorization;
}

/**
 * 处理数组int为string
 * @param $array
 * @return array
 */
function deal_arr_int_to_string($array){
    $arr = [];
    foreach($array as $k => $v){
        $arr[$k] = (string)$v;
    }
    return $arr;
}

/**
 * 随机字符串
 * @param $len
 * @return string
 */
function get_rand_str($len){
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $str ='';
    for($i = 0;$i < $len;$i++){
        $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
}

/**
 * 处理url参数
 * @param $url_params
 * @return string
 */
function deal_url_params($url_params){
    ksort($url_params);
    $buff = '';
    foreach($url_params as $k => $v){
        if($k != 'sign') {
            $buff .= $k . '=' . $v . '&';
        }
    }
    $buff = trim($buff, '&');
    return $buff;
}

/**
 * 处理数组转为xml
 * @param $arr
 * @return string
 */
function deal_array_to_xml($arr){
    $xml = '<xml>';
    foreach ($arr as $key => $val){
        if(is_array($val)){
            $xml .= '<' . $key . '>' . deal_array_to_xml($val) . '</' . $key . '>';
        }else{
            $xml .= '<' . $key . '>' . $val . '</' . $key . '>';
        }
    }
    $xml .= '</xml>';
    return $xml;
}